import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'
import { Modal, Toast } from 'ng-zorro-antd-mobile';
import { FormBuilder, FormGroup } from '@angular/forms';
import { SendCodeService } from './service/send-code.service';

@Component({
    selector: 'send-code',
    templateUrl: './send-code.component.html',
    styleUrls: ['./send-code.component.scss'],
    providers: [Modal, Toast]
})
export class SendCodeComponent {

    public codeForm: FormGroup;
    public footer: any;
    public number: any;
    public lessFont: any;
    public isCanSend: boolean = false;
    public lessInterval: any;


    @Input() isShow: boolean = false;
    @Input() phone: any;
    @Output() sendCode = new EventEmitter<any>()
    @Output() close = new EventEmitter<any>()

    constructor(
        private _modal: Modal,
        private _toast: Toast,
        private fb: FormBuilder,
        private service: SendCodeService,
    ) { }

    ngOnInit() {

        // this.sendPhoneCode();

        this.codeForm = this.fb.group({
            code: ['']
        });

        this.footer = [
            {
                text: '取消',
                onPress: () => {
                    console.log('取消');
                    this.isShow = false;
                    this.onClose();

                }
            },
            {
                text: '确定',
                onPress: () => {
                    console.log('确定');
                    console.log(this.codeForm.value['code']);
                    let code = this.codeForm.value['code']
                    if (code) {
                        this.sendCodeModal(code);

                    } else {
                        Toast.fail('验证码不能为空', 1000)
                    }

                }
            }
        ];

    }

    onClose() {
        this.close.emit();
    }

    sendPhoneCode() {

        this.numberLess();

        // Toast.success('验证码发送成功', 1000)
        this.service.sendCode({
            "mode": "CaptchaMode_Mobile", 
            "target": this.phone
        }, res => {
            console.log(res);
            // Toast.success('验证码发送成功', 1000)
        })


    }

    numberLess() {

        this.clearInterval();

        this.lessInterval = setInterval(() => {
            this.number--
            this.lessFont = this.number + '秒'

            if (this.number <= 0) {
                this.lessFont = "重新发送";
                clearInterval(this.lessInterval)
                this.isCanSend = true;
            }
        }, 1000);
    }


    sendCodeModal(code) {

        this.clearInterval();

        this.isShow = false;
        this.sendCode.emit(code);
    }

    clearInterval() {
        clearInterval(this.lessInterval)
        this.isCanSend = false;
        this.number = 60;
        this.lessFont = "60秒"
    }

}